<template>
    <!-- 图书列表 -->
    <div class="book-wrapper" v-if="props.modelValue.length">
        <div class="book-item" v-for="item in props.modelValue">
            <div class="book-cover" @click="toReaderPage(item.key, item.name, item.format)">
                <template v-if="item.cover"></template>
                <template v-else>
                    <div class="format" :style="{ backgroundColor: formatColorMap[item.format] }">{{ item.format }}
                    </div>
                    <div class="name text-clip text-justify">{{ item.name }}</div>
                </template>
            </div>
            <div class="font-style text-clip text-justify book-name">{{ item.name }}</div>
            <div class="opt font-style">
                <div class="percent">{{ item.percentage }}%</div>
                <el-popover placement="right" :width="200" trigger="click">
                    <template #reference>
                        <Icon class="icon" color="#2d4059" name="more" width="20" height="20" />
                    </template>
                    <div class="menu-box" v-if="OptMenus.length > 0">
                        <template v-for="menuItem in OptMenus">
                            <div class="menu-item" @click="clickMenu(menuItem.code, item.key, item.name)">
                                <Icon color="#2d4059" :name="menuItem.icon" width="18" height="18" />
                                <span>{{ menuItem.name }}</span>
                            </div>
                        </template>
                    </div>
                </el-popover>
            </div>
        </div>

    </div>
    <!-- 添加到书架弹窗 -->
    <el-dialog title="添加到书架" v-model="dialogVisible" width="400px" @close="resetForm">
        <el-form :model="formData" :rules="rules" ref="formRef">
            <el-form-item label="选择">
                <el-select v-model="formData.selectShelfKey" placeholder="选择书架" size="large">
                    <el-option v-for="item in catalogStore.catalogs" :key="item.key" :label="item.name"
                        :value="item.key" />
                </el-select>
            </el-form-item>
            <el-form-item label="新建" prop="name">
                <el-input v-model="formData.name" placeholder="请输入文件夹名称" size="large" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="addBookToShelf">确定</el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 图书详情弹窗 -->
    <el-dialog title="图书详细信息" v-model="bookDetaildialogVisible" width="380px" center draggable :show-close="false">
        <div class="book-detail">
            <div class="book-item">
                <div class="book-cover">
                    <template v-if="bookInfo.cover"></template>
                    <template v-else>
                        <div class="format" :style="{ backgroundColor: formatColorMap[bookInfo.format] }">{{
                            bookInfo.format }}
                        </div>
                        <div class="name text-clip text-justify">{{ bookInfo.name }}</div>
                    </template>
                </div>
            </div>
            <div class="book-name">{{ bookInfo.name }}</div>
            <div class="book-info-table">
                <table class="table">
                    <tbody>
                        <tr class="thead">
                            <td class="col">出版商</td>
                            <td class="col">文件大小</td>
                            <td class="col">添加于</td>
                            <td class="col">格式</td>
                        </tr>
                        <tr>
                            <td class="col">{{ bookInfo.publisher || '' }}</td>
                            <td class="col">{{ sizeFormat || '' }}</td>
                            <td class="col">{{ bookInfo.createTime || '' }}</td>
                            <td class="col">{{ bookInfo.format || '' }}</td>
                        </tr>
                    </tbody>

                </table>
            </div>
            <div class="book-description">描述：{{ bookInfo.description }}</div>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="bookDetaildialogVisible = false">关闭</el-button>
            </span>
        </template>
    </el-dialog>

</template>
<script setup lang="ts">
import type { BookInfoAndReadRecord, Book } from "@/types/book";
import { menuTypeEnum } from '@/types/book';
import Icon from "../Icon/icon.vue";
import { useBookStore, useCatalogStore } from "@/modules/manager/stores";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from 'element-plus'
import indexedDB from '@/utils/indexedDB'
import { isObject } from "@/utils/tools";

interface BookProps {
    modelValue: BookInfoAndReadRecord[],
    menuType: menuTypeEnum,
    shelfKey?: string,
}

const emit = defineEmits<{
    (e: 'update:modelValue', value: BookInfoAndReadRecord[]): void
}>()
const bookStore = useBookStore();
const catalogStore = useCatalogStore();
const props = defineProps<BookProps>();
let OptMenus = reactive([
    { code: 'detail', name: '详细信息', icon: 'detail' },
])
const formatColorMap: { [key: string]: string } = {
    'PDF': '#DD0011',
    'TXT': '#FBBF10',
    'DOC': '#185ABD',
    'DOCX': '#185ABD'
}
const dialogVisible = ref(false);
const formRef = ref<FormInstance>();
const formData = reactive({
    selectShelfKey: '',
    name: ''
});
let currentClickBook = {
    key: '',
    name: ''
}
const bookInfo = ref<Book>({
    name: '',
    key: '',
    createTime: '',
    updateTime: '',
    author: '',
    cover: '',
    format: '',
    publisher: '',
    size: 0,
})
const bookDetaildialogVisible = ref(false)
const initOptMenu = (type: menuTypeEnum) => {
    let menus = [
        { code: 'heart', name: '添加到喜爱', icon: 'heart' },
        { code: 'file', name: '添加到书架', icon: 'file' },
        { code: 'delete', name: '移除', icon: 'delete' },
        { code: 'reset', name: '恢复', icon: 'reset' },
        { code: 'detail', name: '详细信息', icon: 'detail' },
    ]
    if (type == menuTypeEnum.Favorite || type == menuTypeEnum.Shelf) {
        OptMenus = menus.filter(item => item.code == 'delete' || item.code == 'detail')
    } else if (type == menuTypeEnum.RecycleBin) {
        OptMenus = menus.filter(item => item.code == 'reset')
    } else {
        // 全部图书
        OptMenus = menus.filter(item => item.code != 'reset')
    }
}
// 添加 watch 来监听初始值
watch(
    () => props.menuType,
    (newValue) => {
        initOptMenu(newValue)
    },
    { immediate: true }
)

const clickMenu = (clickType: string, bookKey: string, bookName: string): void => {
    currentClickBook.key = bookKey
    currentClickBook.name = bookName
    switch (clickType) {
        case 'heart': addToFavorit(bookKey); break;
        case 'file': dialogVisible.value = true; break;
        case 'delete': handleDeleteBook(bookKey, bookName); break;
        case 'reset': handleReset(bookKey); break;
        case 'detail': openDetailDialogAndGetDetail(bookKey); break;
    }
}
// 添加到我的喜爱
const addToFavorit = (key: string): void => {
    bookStore.addFavoriteBooks(key).then(res => {
        if (res) {
            ElMessage.success('添加成功！')
        }
    }).catch(msg => {
        ElMessageBox.alert(msg, '提示', { type: 'error', confirmButtonText: '关闭' });
    });
}

// 添加到书架&新增书架
const rules = reactive<FormRules>({
    name: [
        // { required: true, message: '请输入文件夹名称', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
    ],
})

const resetForm = () => {
    if (formRef.value) {
        formRef.value.resetFields()
    }
    formData.selectShelfKey = '';
    formData.name = '';
}
const addBookToShelf = () => {
    if (!formRef.value) return;
    formRef.value.validate((valid: boolean) => {
        if (valid) {
            try {
                if (formData.selectShelfKey) {
                    // 选择书架
                    catalogStore.pushBookToCatalog(formData.selectShelfKey, currentClickBook.key).then(() => {
                        ElMessage.success('添加成功！')
                    })
                } else {
                    // 新增书架
                    catalogStore.addCatalog(formData.name, currentClickBook.key).then(() => {
                        ElMessage.success('添加成功！')
                    })
                }
            } catch (error) {
                let msg = typeof error == 'string' ? error : '添加失败！';
                ElMessageBox.alert(msg, '提示', { type: 'error', confirmButtonText: '关闭' });
            }

            dialogVisible.value = false
            resetForm()
        }
    })
}

// 移除图书菜单
const handleDeleteBook = (bookKey: string, bookName: string) => {
    // 判断是否从 全部图书/我的喜爱/书架/全部图书中操作移除
    switch (props.menuType) {
        case menuTypeEnum.All:
            // 从全部图书中操作移除，移到回收站
            ElMessageBox.confirm(
                `将图书为【${bookName}】移到回收站，确定要操作吗？`,
                '提示',
                {
                    type: 'warning',
                    confirmButtonText: '确定',
                    cancelButtonText: '取消'
                })
                .then(() => {
                    bookStore.moveBookToRecycle(bookKey).then(() => {
                        updateBookList(bookKey)
                        ElMessage.success('已将图书移到回收站！')
                    }).catch(error => {
                        let msg = typeof error == 'string' ? error : '移除失败！';
                        ElMessage.error(msg)
                    })
                })
            break;
        case menuTypeEnum.Favorite:
            // 从我的喜爱 中移除
            let res = bookStore.deleteFavoriteBook(bookKey);
            if (res) {
                updateBookList(bookKey)
                ElMessage.success('移除成功！')
            } else {
                ElMessage.error('移除失败！')
            }
            break;
        case menuTypeEnum.Shelf:
            // 从书架中 中移除
            if (props.shelfKey) {
                catalogStore.shiftBookFromCatalog(props.shelfKey, bookKey).then(() => {
                    updateBookList(bookKey)
                    ElMessage.success('移除成功！')
                }).catch(e => {
                    ElMessage.error(e as string)
                });

            } else {
                ElMessage.error('无法移除，缺少参数，请重新刷新页面！')
            }

            break;

    }
}

// 在回收站里操作恢复，将图书从回收站中删除
const handleReset = (bookKey: string) => {
    let res = bookStore.removeBookFromRecycle(bookKey);
    if (res) {
        ElMessage.success('图书已恢复，可在全部图书中看到~')
        updateBookList(bookKey)
    } else {
        ElMessage.error('恢复失败，请检查图书是否在回收站~')
    }

}

const openDetailDialogAndGetDetail = (bookKey: string) => {
    indexedDB.get('books').then(books => {
        // 当前这个表存在
        if (books && Array.isArray(books)) {
            const item = books.find(item => item.key == bookKey);
            if (item && isObject(item)) {
                bookInfo.value = item
                bookDetaildialogVisible.value = true
            } else {
                ElMessage.warning('暂未查询到图书~')
            }
        } else {
            ElMessage.warning('暂未查询到图书~')
        }
    }).catch(() => {
        ElMessage.warning('暂未查询到图书~')
    })
}
const updateBookList = (bookKey: string) => {
    let newBookList: BookInfoAndReadRecord[] = []
    newBookList = props.modelValue.filter(item => item.key != bookKey)
    // if(optType == 'delete'){
    //     // 当前操作的是 “删除”，则把对应的bookList数组里的项目给删除
    //     newBookList = props.modelValue.filter(item => item.key != bookKey)
    // }else if(optType == 'reset'){
    //     // 当前操作的是“恢复”，则需要重新根据回收站的数据，重新过滤掉“已恢复”的项目
    //     newBookList = props.modelValue.filter(item => item.key != bookKey)
    // }
    emit('update:modelValue', newBookList)
}
const toReaderPage = (bookKey: string, bookName: string, format: string) => {
    let params = '?bookKey=' + bookKey + '&name=' + bookName + '.' + format
    window.open('/reader.html' + params, '_blank')
}
const sizeFormat = computed(() => {
    return formatSizeUnits(bookInfo.value.size)
})

const formatSizeUnits = (bytes: number) => {
    if (bytes >= 1073741824) { return (bytes / 1073741824).toFixed(2) + " GB"; }
    else if (bytes >= 1048576) { return (bytes / 1048576).toFixed(2) + " MB"; }
    else if (bytes >= 1024) { return (bytes / 1024).toFixed(2) + " KB"; }
    else if (bytes > 1) { return bytes + " B"; }
    else if (bytes == 1) { return bytes + " B"; }
    else { return "0 B"; }
}



</script>

<style scoped lang="scss">
.book-wrapper {
    display: flex;
    flex-wrap: wrap;
}

.book-item {
    box-sizing: border-box;
    width: 110px;
    height: 197px;
    margin: 10px;

    .book-cover {
        width: 100%;
        height: 137px;
        box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.18);
        margin-bottom: 8px;
        overflow: hidden;
        cursor: pointer;

        .format {
            width: 85%;
            height: 30px;
            line-height: 30px;
            margin-top: 10%;
            padding-left: 10%;
            background-color: #FBBF10;
            color: #fff;
        }

        .name {
            padding: 6px 6px 0 6px;
            font-size: 14px;
            font-weight: 500;
        }

    }

    .book-name {
        text-wrap: wrap;
        height: 35px;
        overflow: hidden;
    }

    .opt {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .icon {
            cursor: pointer;
        }
    }

}

.font-style {
    font-size: 12px;
    color: #666;
}

.text-clip {
    // 基于行数截断字符
    line-clamp: 2;
    -webkit-line-clamp: 2;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: clip;

}

.text-justify {
    word-break: break-all; //对英文有效，在溢出处换行
    // 文本两端对其
    text-align: justify; //文字向两侧对齐，对最后一行无效。
    text-justify: auto;
}

// 弹出层-操作菜单
.menu-box {
    .menu-item {
        padding: 8px;
        cursor: pointer;

        &:hover {
            background-color: var(--el-color-info-light-9);
        }

        span {
            margin-left: 10px;
        }
    }
}

// 弹出层-图书详情
.book-detail {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    color: var(--el-text-color-primary);

    .book-item {
        width: 150px;
        height: 197px;
        margin: 0 0 10px 0;

        .book-cover {
            height: 100%;
            margin-bottom: 0;
            cursor: none;
        }
    }

    .book-name,
    .book-info-table,
    .book-description {
        box-sizing: border-box;
        width: 100%;
        padding: 0 20px;

    }

    .book-name {
        font-size: 14px;
        word-wrap: break-word;
        text-align: center;
    }

    .book-info-table {
        font-size: 12px;
        margin: 10px 0;

        table,
        tr {
            border: 0;
            border-spacing: 0;

        }

        td {
            border-right: 1px solid #DCDFE6;
            width: 25%;
            text-align: center;
        }

        tr td:last-child {
            border: 0;
        }

        .thead {
            color: #999;
        }

    }

    .book-description {
        text-align: left;
    }
}
</style>
